package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"seichat/middlerware"
	"seichat/service"
)

type UploadHandler struct {
	uploadSvc service.UploadService
}

func NewUploadHandler(uploadSvc service.UploadService) *UploadHandler {
	return &UploadHandler{
		uploadSvc: uploadSvc,
	}
}

func (u *UploadHandler) RegisterRoutes(router *gin.Engine) {
	group := router.Group("/upload")
	{
		group.Use(middlerware.JWT())
		group.POST("/image", u.UploadImage)
	}
}

func (u *UploadHandler) UploadImage(ctx *gin.Context) {
	// 获取文件
	file, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "请选择文件"})
		return
	}

	src, err := file.Open()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "打开文件失败: " + err.Error()})
		return
	}
	defer src.Close()

	// 调用 Service 层处理上传
	url, err := u.uploadSvc.UploadImage(src, file)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "上传成功",
		"url":     url,
	})
}
